package com.ls.mq.redis;

import com.google.common.base.Preconditions;
import com.sun.istack.internal.Nullable;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
//TODO username ,password
public class RedisFactory {

	private String hostName;
	private int port;
	private String userName;
	private String password;
	public volatile static RedisFactory instance ;
	private RedisFactory(String hostName,int port,@Nullable String userName,@Nullable String password) {
		Preconditions.checkNotNull(hostName);
		Preconditions.checkNotNull(port);
		this.hostName=hostName;
		this.port=port;
		this.userName=userName;
		this.password=password;
	}

	public static RedisFactory initInstance(String hostName,int port,@Nullable String userName,@Nullable String password) {
		if (instance == null)
			synchronized (RedisFactory.class) {
				if (instance == null)
					instance = new RedisFactory(hostName,port,userName,password);
			}
		return instance;
	}
	
	public static RedisFactory getInstance(){
		if(instance!=null)
			return instance;
		throw new IllegalStateException("Redis Factory Is Not Initalized");
	}

	private JedisPool pool;

	public synchronized void initPool() {
		if (pool == null){
			pool = new JedisPool(new JedisPoolConfig(), getHostName(), getPort());
		}
			
	}

	public Jedis getClient() {
		if (pool == null)
			initPool();
		return pool.getResource();
	}

	public String getHostName() {
		return hostName;
	}

	public void setHostName(String hostName) {
		this.hostName = hostName;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public JedisPool getPool() {
		return pool;
	}

	public void setPool(JedisPool pool) {
		this.pool = pool;
	}
	
}
